package com.navinfo.opentsp.user.web.controller;

import com.navinfo.opentsp.user.common.util.date.DateUtil;
import com.navinfo.opentsp.user.dal.entity.UserEntity;
import com.navinfo.opentsp.user.dal.entity.UserLoginLogEntity;
import com.navinfo.opentsp.user.service.param.login.*;
import com.navinfo.opentsp.user.service.result.CommonResult;
import com.navinfo.opentsp.user.service.result.ResultCode;
import com.navinfo.opentsp.user.service.resultdto.login.LoginHistory;
import com.navinfo.opentsp.user.service.resultdto.login.LoginResult;
import com.navinfo.opentsp.user.service.user.OauthLoginService;
import com.navinfo.opentsp.user.service.user.UserService;
import com.navinfo.opentsp.user.web.autologin.AutoLoginHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wupeng
 * @version 1.0
 * @date 2015-10-14
 * @modify
 * @copyright Navi Tsp
 */
@RestController
@RequestMapping("/user")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private OauthLoginService oauthLoginService;
    @Autowired
    private AutoLoginHelper autoLoginHelper;

    @RequestMapping(value = "/login", method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public CommonResult<LoginResult> login(HttpServletRequest request, HttpServletResponse response, @RequestBody LoginParam loginParam){
        CommonResult<LoginResult> loginResultCommonResult = this.userService.login(loginParam);
        if(loginParam.getAutoLogin() != null && loginParam.getAutoLogin().intValue() == 1 &&
                loginResultCommonResult.getCode() == ResultCode.SUCCESS.code()) {//如果登录成功了
            this.autoLoginHelper.setAutoLogin(request, response, loginParam);
        }
        return loginResultCommonResult;
    }

    @RequestMapping(value = "/loginHistory", produces = {"application/json; charset=utf-8"})
    public CommonResult<List<LoginHistory>> latestHistory(LatestLoginHistory history) {
        UserEntity userEntity = history.getUser();
        if (userEntity == null || StringUtils.isEmpty(userEntity.getId())) {
            return new CommonResult<List<LoginHistory>>().fillResult(ResultCode.NOT_LOGIN);
        }

        //TODO extract this number to param
        List<UserLoginLogEntity> entities = this.userService.latestLoginLog(userEntity.getId(), 10);
        List<LoginHistory> histories = new ArrayList<>(entities.size());
        for (UserLoginLogEntity entity : entities) {
            LoginHistory history1 = new LoginHistory();
            history1.setIp(entity.getLoginIp());
            history1.setDevice(entity.getDeviceType());
            history1.setLoginTime(DateUtil.formatTime(entity.getLoginTime()));
            histories.add(history1);
        }

        return new CommonResult<List<LoginHistory>>().fillResult(ResultCode.SUCCESS).setData(histories);
    }

    /**
     * 如果token未过期，刷新token会产生一个新的token
     * 如果token已过期，则会提示token过期，需要重新登录
     *
     * @param request
     * @param tokenParam
     * @return
     */
    @RequestMapping(value = "/refreshToken", produces = {"application/json; charset=utf-8"})
    public CommonResult<LoginResult> refreshToken(HttpServletRequest request, @RequestBody RefreshTokenParam tokenParam){
        return this.userService.refreshToken(tokenParam);
    }

    @RequestMapping(value = "/validateToken", produces = {"application/json; charset=utf-8"})
    public CommonResult<LoginResult> validateToken(HttpServletRequest request, ValidateTokenParam tokenParam){
        UserEntity userEntity = tokenParam.getUser();
        if(userEntity != null) {
            return CommonResult.newInstance(ResultCode.SUCCESS, LoginResult.class)
                    .setData(new LoginResult(userEntity.getId(), userEntity.getNickname(), tokenParam.getToken()));
        } else {
            return CommonResult.newInstance(ResultCode.TOKEN_INVALID, LoginResult.class);
        }
    }

    @RequestMapping(value = "/quickLogin", method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public CommonResult<LoginResult> quikLogin(@RequestBody QuickLoginParam loginParam){
        return this.userService.quickLogin(loginParam);
    }

    @RequestMapping(value = "/thirdLogin", method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public CommonResult<LoginResult> thirdLogin(@RequestBody OauthLoginParam oauthLoginParam){
        return this.oauthLoginService.oauthLogin(oauthLoginParam);
    }

    @RequestMapping(value = "/logout", method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public CommonResult<String> thirdLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody LogoutParam logoutParam){
        CommonResult<String> result =  this.userService.logout(logoutParam);
        autoLoginHelper.deleteLogin(request, response, logoutParam);
        return result;
    }

}
